<script>
export default {
  name: 'tz-table',
  inheritAttrs: false,
  props: {
    data: {
      type: Function,
      required: true
    },
    showLoading: {
      type: Boolean,
      default: true
    },
    // 是否展示分页
    pagination: {
      type: Boolean,
      default: true
    },
    // 是否展示斑马纹
    stripe: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dataList: [],
      total: 0,
      loading: false,
      pageSize: 10,
      currentPage: 1
    }
  },
  methods: {
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @bool Boolean
     */
    refresh(bool = true) {
      if (bool) {
        this.currentPage = 1
      }
      this.loadData()
    },
    /**
     * 加载数据方法
     */
    loadData() {
      this.$nextTick(() => {
        if (this.loading) {
          return
        }
        const result = this.data({
          pageNum: this.currentPage,
          pageSize: this.pageSize
        })
        this.loading = true
        result.then(res => {
          this.dataList = res?.data || []
          this.total = res?.total || 0
        }).finally(() => {
          this.loading = false
        })
      })
    },
    sizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.loadData()
    },
    currentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    getRef(name = 'table') {
      return this.$refs[name]
    },
    getCellStyle({column}){
      // TODO 针对Safari表格width与showOverflowTooltip暂不能共存异常
      const tempWidth = column.realWidth || column.width
      if(column.width) {
        return {
          minWidth:tempWidth + 'px',
          maxWidth:tempWidth + 'px'
        }
      }
      return {}
    }
  },
  created() {
    this.loadData()
  },
  computed: {
    paginationProps() {
      return {
        total: this.total || 0,
        layout: 'total, sizes, prev, pager, next, jumper',
        pageSizes: [10, 30, 50, 100],
        ...this.$attrs,
        pageSize: this.pageSize,
        currentPage: this.currentPage
      }
    }
  },
  render() {
    return <div class="table-wrapper" v-loading={this.loading && this.showLoading}>
      <el-table ref="table"
        cellStyle={ this.getCellStyle }
        on={ this.$listeners }
        attrs={{...this.$attrs, data: this.dataList, stripe: this.stripe}}
        scopedSlots={ this.$scopedSlots }>
        {Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>))}
      </el-table>
      <div class="flex-row">
        <div class="flex1"/>
        {(() => {
          if (this.pagination) {
            return <el-pagination
              ref="pagination"
              style="margin-top: 10px"
              attrs={{...this.paginationProps}}
              onSize-change={this.sizeChange}
              onCurrent-change={this.currentChange}
            />
          }
        })()}
      </div>
    </div>
  }
}
</script>

<style scoped>

</style>
